/*jslint browser: true*/
Model = (function () {
  'use strict';

  var
    configMap = {
      anon_sid : -1
    },

    stateMap  = {
      anon_user : null,
      people_sid_map : {},
      cur_user : null
    },

    personProto, makePerson, removePerson, people, initModule;

  personProto = {
    get_is_user : function () {
      return this.sid === stateMap.user.sid;
    }
  };

  makePerson = function (person_map) {
    let person, sid = person_map.sid;
    if (!sid) {
      throw 'sid is required!!';
    }
    person         = Object.create(personProto);
    person.sid     = person_map.sid;
    person.uid = person_map.uid;
    person.channelInfo = person_map.channelInfo;
    person.chatType = person_map.chatType;// 进线渠道
    person.bizType = person_map.bizType; // 业务类型
    person.content = person_map.content;// 聊天输入框内容
    person.tagContent = person_map.tagContent;// 标签内容
    person.tagContentArray = person_map.tagContentArray;// 添加客户标签时存储数据
    person.kbpContent = person_map.kbpContent;// 知识随行内容
    person.busiTypeId = person_map.busiTypeId;// 交互小结业务分类
    person.bizContent = person_map.bizContent;// 交互小结业务内容
    person.ivrContent = person_map.ivrContent;// ivr来访轨迹
    person.chatState = person_map.chatState;// 会话状态
    person.lastMsg = person_map.lastMsg;
    person.chatMode = '';
    person.extension = person_map.extension;
    person.clientInfo = '';
    person.userData = person_map.userData;
    person.callType = person_map.callType;
    person.otherconnid = person_map.otherconnid;
    person.username = person_map.username;
    person.interChatAgent = person_map.interChatAgent;

    stateMap.people_sid_map[sid] = person;
    return person;
  };

  removePerson = function(person) {
    if(!person) {
      return false;
    }

    if(person.sid) {
      delete stateMap.people_sid_map[person.sid];
      stateMap.cur_user = stateMap.anon_user;
      globalUiKit.vm.$emit(globalUiKit.globalEvent.EVENT_REMOVE_USER, {sessionId: person.sid})
      globalUserData.closeTab(person.sid)
      // 没有客户时 reset 客户信息
      if(stateMap.people_sid_map && Object.keys(stateMap.people_sid_map).length == 0) {
        globalUiKit.vm.$emit(globalUiKit.globalEvent.ACTION_CHANGE_CURRENT_USER, {user: 'anon_user'})
      }
      if(window.CONFIG.debugAll) {
        console.log(new Date() + ", log info [remove person: " + person.sid + "]")
      }
      return true;
    }
    return false;
  };

  people = (function () {
    let get_by_sid, get_user, change_user, set_chatState, get_chatState, set_bizType, get_bizType, set_inputContent, get_inputContent, set_bizContent, get_bizContent, set_position, get_position, on_begin_chat, update_user,
      on_exit_chat, setLastMsg, getLastMsg, setNoReadMsgNum, getNoReadMsgNum, get_all_users, get_users_by_channeltype, get_totalusers_by_channeltype, get_chat_users;

    get_by_sid = function (sid) {
      return stateMap.people_sid_map[sid];
    };

    get_all_users = function () {
      let obj = stateMap.people_sid_map;
      if(window.CONFIG.debugAll) {
        console.log("当前会话列表信息:" + JSON.stringify(obj));
      }
      return obj;
    };

    get_user = function () { return stateMap.cur_user; };

    change_user = function(sid, update) {
      if(stateMap.people_sid_map[sid]) {
        stateMap.cur_user = stateMap.people_sid_map[sid]
        stateMap.cur_user.update = update //切换用户，通知强制更新（适用于来回转，随路数据变化的情况）
        globalUiKit.vm.$emit(globalUiKit.globalEvent.ACTION_CHANGE_CURRENT_USER, stateMap.cur_user)
        //给右侧iframe发送消息
        globalUserData.changeCurrentUser(sid, stateMap.cur_user.chatType);
        return true;
      }
    };
    update_user = function(sid) {
      if(stateMap.people_sid_map[sid]) {
        globalUiKit.vm.$emit('update_user', stateMap.people_sid_map[sid])
        if(stateMap.cur_user.sid == sid) {
          Model.people.change_user(sid, 'update')
        }
      }
    };
    set_chatState = function (chatState, sid) {
      if (sid) {
        let tUser = get_by_sid(sid);
        if(tUser){
          tUser.chatState = chatState;
          globalUiKit.vm.$emit(globalUiKit.globalEvent.EVENT_CHAT_STATUES_CHANGE, tUser)
          var tempUser = JSON.parse(localStorage.getItem('interactUser_' + tUser.sid) || '{}');
          tempUser.chatState = chatState
          localStorage.setItem('interactUser_' + tempUser.sid, JSON.stringify(tempUser))
        }
      }
    };

    get_chatState = function (sid) {
      if(sid) {
        let tUser = get_by_sid(sid);
        if(tUser && tUser.chatState) {
          return tUser.chatState;
        }
      }
      // 默认状态
      return Constants.requestNameMap.Normal;
    };

    // 设置输入框内容
    set_inputContent = function(content, sid) {
      if (sid) {
        let tUser = get_by_sid( sid );
        if(tUser){
          tUser.content = content;
        }
      }
    };

    // 获取输入框内容
    get_inputContent = function (sid) {
      if(sid) {
        let tUser = get_by_sid( sid );
        if(tUser && tUser.content) {
          return tUser.content;
        }
      }
      return "";
    };

    // 设置业务活动种类
    set_bizType = function (bizType, sid) {
      if (sid) {
        let tUser = get_by_sid( sid );
        if(tUser){
          tUser.busiTypeId = bizType;
        }
      }
    };

    // 获取业务活动种类
    get_bizType = function ( sid) {
      if(sid) {
        let tUser = get_by_sid( sid );
        if(tUser && tUser.busiTypeId) {
          return tUser.busiTypeId;
        }
        return '';
      }
    };

    // 设置小结内容
    set_bizContent = function (bizContent, sid) {
      if (sid) {
        let tUser = get_by_sid( sid );
        if(tUser){
          tUser.bizContent = bizContent;
        }
      }
    };

    // 获取小结内容
    get_bizContent = function (sid) {
      if(sid) {
        let tUser = get_by_sid(sid);
        if(tUser && tUser.bizContent) {
          return tUser.bizContent;
        }
        return '';
      }
    };

    // 初始化用户信息(userData之后的参数为电话专有)
    on_begin_chat = function (sid, uid, channelInfo, chatType, extension, chatState, bizType, content, userData, callType, otherconnid, username) {
      // 1.if exist
      if(stateMap.people_sid_map[sid]) {
        if(Settings.debugAll)  console.log(new Date() + ", log info [" + sid + " is existed!! ]");
        return false;
      }

      // 2.make person
      let tUser = makePerson({
        sid : sid,
        uid : uid,
        channelInfo : channelInfo,
        chatType : chatType,
        chatState : chatState,
        bizType : bizType,
        // 聊天输入框内容
        content: content,
        // 客户标签
        tagContent: '',
        tagContentArray: [],
        // 知识随行
        kbpContent: '',
        // 交互小结业务分类
        busiTypeId : '',
        // 交互小结业务内容
        bizContent : '',
        ivrContent: '',
        lastMsg : "",
        robotSessionId : "",
        extension : extension,
        userData: userData,
        callType: callType,
        otherconnid: otherconnid,
        username: username,
        // 内部会议座席
        interChatAgent: []
      });
      // 存localStorage,刷新恢复页签用
      localStorage.setItem('interactUser_' +sid, JSON.stringify(tUser || {}))
      // 增加user时候，创建页签
      var obj = {};
      if(chatType != 'call'){
        obj = {
          sessionId: sid,
          channelType: chatType,
          chatState: chatState,
          userName: username,
          fromUser: uid
        };
      }else{
        obj = {
          sessionId: sid,
          otherconnid: otherconnid,
          channelType: chatType,
          calltype:  callType,
          otherDn: uid,
          userName: username
        };
      }
      window.globalUiKit.vm.$emit('addRecordList', obj);
    };

    on_exit_chat = function (sid) {
      if(sid){
        //1. remove person
        if (stateMap.people_sid_map[ sid ]) {
          removePerson(stateMap.people_sid_map[ sid ]);
        }
        localStorage.removeItem('interactUser_' + sid);
      }
    };
    get_users_by_channeltype  = function (channeltype) {
       var num = 0;
       let obj = stateMap.people_sid_map;
       Object.keys(obj).forEach(function(key) {
        if(stateMap.people_sid_map[key].chatType == channeltype && Constants.chatDoneStatus.indexOf(stateMap.people_sid_map[key].chatState) == -1){
          num++;
        }
      });
      return num;
    };
    get_totalusers_by_channeltype  = function (channeltype) {
      var num = 0;
      let obj = stateMap.people_sid_map;
      Object.keys(obj).forEach(function(key) {
        if(stateMap.people_sid_map[key].chatType == channeltype){
          num++;
        }
      });
      return num;
    };
    get_chat_users  = function () {
      var num = 0;
      let obj = stateMap.people_sid_map;
      Object.keys(obj).forEach(function(key) {
        if(stateMap.people_sid_map[key].chatType != 'call' && Constants.chatDoneStatus.indexOf(stateMap.people_sid_map[key].chatState) == -1){
          num++;
        }
      });
      return num;
    };
    setLastMsg = function (sid, obj) {
      if(stateMap.people_sid_map[sid]) {
        stateMap.people_sid_map[sid].lastMsg = obj.msg;
        stateMap.people_sid_map[sid].lastMsgType = obj.msgtype;
        if(obj.msgtype && obj.msgtype != ""){
          obj.sessionId = sid;
          globalUiKit.vm.$emit('lastMsg', obj)
        }
      }
    };

    getLastMsg = function (sid) {
      if(stateMap.people_sid_map[ sid ]) {
        return stateMap.people_sid_map[sid].lastMsg;
      }
    };

    setNoReadMsgNum = function (sid, num) {
      if(stateMap.people_sid_map[ sid ]) {
        stateMap.people_sid_map[sid].noReadMsgNum = num;
        if (num == 0) {
          num = ''
        }
        globalUiKit.vm.$emit('noReadMsgNum', {sessionId:sid, noReadMsgNum:num})
      }
    };

    getNoReadMsgNum = function (sid) {
      if(stateMap.people_sid_map[ sid ]) {
        return stateMap.people_sid_map[sid].noReadMsgNum || 0;
      }
    };

    return {
      get_by_sid : get_by_sid,
      get_user : get_user,
      change_user : change_user,
      update_user: update_user,
      set_chatState : set_chatState,
      get_chatState : get_chatState,
      set_bizType : set_bizType,
      set_inputContent : set_inputContent,
      get_inputContent : get_inputContent,
      set_bizContent : set_bizContent,
      on_begin_chat : on_begin_chat,
      on_exit_chat : on_exit_chat,
      get_all_users : get_all_users,
      setLastMsg : setLastMsg,
      getLastMsg : getLastMsg,
      setNoReadMsgNum: setNoReadMsgNum,
      getNoReadMsgNum: getNoReadMsgNum,
      get_users_by_channeltype: get_users_by_channeltype,
      get_totalusers_by_channeltype: get_totalusers_by_channeltype,
      get_chat_users: get_chat_users
    };
  }());

  initModule = function () {
    stateMap.anon_user = makePerson({
      sid  : configMap.anon_sid,
      uid  : 'anonymous',
      chatType : null
    });
    stateMap.user = stateMap.anon_user;
  };

  return {
    initModule : initModule,
    people     : people
  };
}());

/**
 * 座席信息
 *
 * @type {{}}
 */
Model.Agent = {
  // 基本信息
  userId      : '',
  agentName   : '',
  agentId     : '',
  tenantId    : '',
  // 座席昵称
  nickName    : '',

  // 分机
  extension   : '',
  // placeId
  placeId     : '',
  // 交换机id
  switchId : '',
  // SIP Server地址
  sipServer : '',

  // 座席类型
  agentType   : '',
  // 多媒体渠道类型
  chatMediaType : '',
  // 支持的渠道
  channelType : '',
  // 班长级别
  captainLevel: -1,
  // 服务能力
  serviceAbility: -1,
  // 角色信息
  role : '',
  // 组织机构
  orgCode: '',
  // 行政机构编号
  department : '',
  // 行政机构名称
  departName: '',
  // 行政组编号
  groupNames: '',
  // 行政组名称
  orgName: '',
  // 技能组
  skillList: '',
  // 座席技能
  agentSkill: '',
  // 用户组
  userGroupNames: '',

  /**
   * 座席状态 9小休 1就绪
   *  - chat  多媒体渠道
   *  - voice 电话渠道
   *  - global 全局状态
   */
  agentStatus: {
    chat: 0,
    voice: 0,
    global: 0,
  },

  MEDIA: {
    PHONE: 'call',
    CHAT: 'unichat',
  },

  CAPTAIN_LEVEL: {
    NORMAL: '1',
    CAPTAIN: '2',
  },
};

/** 兼容老版本 **/
window.Agent = {}
window.Agent.getCurrentAgent = function () {
  return Model.Agent;
}
